package com.bwsoft.admin.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.hibernate.Query;
import org.springframework.stereotype.Service;

import com.bwsoft.admin.domain.News;
import com.bwsoft.admin.domain.NewsCategory;
import com.bwsoft.admin.domain.valueObject.NewsVO;
import com.bwsoft.admin.service.NewsService;
import com.bwsoft.api.util.Constant;
import com.bwsoft.domain.Dictionary;
import com.bwsoft.model.Message;
import com.bwsoft.util.UploadFileUtil;
import com.bwsoft.util.ValidatorUtil;

@Service(NewsService.NAME)
public class NewsServiceImpl extends BaseServiceImpl_ybd implements NewsService {
	private static Logger LOG = Logger.getLogger(NewsServiceImpl.class.getClass());

	
	/**
	 * 富文本编辑器内软 格式转换
	 * @param str
	 * 		要转换的内容
	 * @return
	 */
	private String htmlspecialchars(String str) {
		str = str.replaceAll("&", "&amp;");
		str = str.replaceAll("<", "&lt;");
		str = str.replaceAll(">", "&gt;");
		str = str.replaceAll("\"", "&quot;");
		return str;
	}
	
	@Override
	public List<News> findAll(Integer category){
		List<News> newsData;
		if (category == null || "".equals(category)) {
			StringBuffer newsHql = new StringBuffer();
			newsHql.append("from News as news ");
			newsData = newsDao.findByHql(newsHql.toString());
//			newsData = newsDao.findAll();
		} else {
			StringBuffer newsHql = new StringBuffer();
			newsHql.append("from News as news where news.category.id = '"+category+"'");
			newsData = newsDao.findByHql(newsHql.toString());
		}
		return newsData;
	}
	
	
	
	@Override
	public List<News> findData(Integer page, Integer rows,  String s_category, String s_lunboFlag, String s_title, String s_status) {
		StringBuffer newsHql = new StringBuffer();
		newsHql.append("from News as news where 1=1 ");
		if(s_category != null && !"".equals(s_category.trim())){
				newsHql.append("and news.category.id = '"+s_category.trim()+"'");
		}
		if(s_lunboFlag != null && !"".equals(s_lunboFlag.trim())){
			newsHql.append("and news.lunboFlag = '"+s_lunboFlag.trim()+"'");
		}
		if(s_title != null && !"".equals(s_title.trim())){
			newsHql.append("and news.title like '%"+s_title.trim()+"%'");
		}
		if(s_status != null && !"".equals(s_status.trim())){
			newsHql.append("and news.status = '"+s_status.trim()+"'");
		}
		newsHql.append(" order by news.addTime desc");
		List<News> newsData=newsDao.findPage(newsHql.toString(), rows, (page - 1) * rows);
		
		return newsData;
	}

	@Override
	public int getTotalCount(String s_category, String s_lunboFlag, String s_title, String s_status) {
		StringBuffer newsHql = new StringBuffer();
		newsHql.append("select count(*) from News as news where 1=1 ");
		if(s_category != null && !"".equals(s_category.trim())){
				newsHql.append("and news.category.id = '"+s_category.trim()+"'");
		}
		if(s_lunboFlag != null && !"".equals(s_lunboFlag.trim())){
			newsHql.append("and news.lunboFlag = '"+s_lunboFlag.trim()+"'");
		}
		if(s_title != null && !"".equals(s_title.trim())){
			newsHql.append("and news.title like '%"+s_title.trim()+"%'");
		}
		if(s_status != null && !"".equals(s_status.trim())){
			newsHql.append("and news.status = '"+s_status.trim()+"'");
		}
		int count=0;
		count = Integer.valueOf(newsDao.findByHql(newsHql.toString()).get(0).toString());
		return count;
	}

	@Override
	public Message checkNewsInput(News news) {
		Message msg = new Message();
		try {
			
			//拼装查询HQL
			StringBuffer sb=new StringBuffer();
			sb.append("from News news where 1=1 ");
			if(news.getTitle()!=null&&!news.getTitle().trim().equals("")){
				sb.append(" and news.title='"+news.getTitle()+"'");
			}
			if(news.getNewsId()!=null){
				sb.append(" and news.id !='"+news.getNewsId()+"'");
			}
			LOG.info("检查字典的Form表单重复的HQL"+sb.toString());
			//根据拼装的hql来查询Dictionary集合
			List<Dictionary> dicList=newsDao.findByHql(sb.toString());
			if(dicList.size()==0){
				msg.setMsgFlag(true);
				msg.setMsgStr("数据库中暂无此值");
			}else{
				msg.setMsgFlag(false);
				msg.setMsgStr("数据库已存在此值");
			}
		} catch (Exception e) {
			msg.setMsgFlag(false);
			msg.setMsgStr("添加失败：" + e.toString());
			LOG.info(e);
		}
		return msg;
	}

	@Override
	public Message saveNews(News news, File suolveImg, String suolveImgFileName, File lunboImg, String lunboImgFileName) {
		Message msg = new Message();
		try {
			//---------缩略图上传---------------
			if(suolveImg != null && !"".equals(suolveImg)){
				String suolveRealpath = ServletActionContext.getServletContext().getRealPath(Constant.PATH_IMG_SUOLVE);
				String suolveFileName=null ;
				suolveFileName=UUID.randomUUID().toString()+suolveImgFileName.substring(suolveImgFileName.lastIndexOf('.'), suolveImgFileName.length());
				UploadFileUtil.uploadOneFile(suolveFileName, suolveImg, suolveRealpath);
				news.setImgURL(Constant.PATH_IMG_SUOLVE+"/"+suolveFileName);
			}
			//---------轮播图上传---------------
			if(lunboImg != null && !"".equals(lunboImg)){
				String lunboRealpath = ServletActionContext.getServletContext().getRealPath(Constant.PATH_IMG_LUNBO);
				String lunboFileName=null ;
				lunboFileName=UUID.randomUUID().toString()+lunboImgFileName.substring(lunboImgFileName.lastIndexOf('.'), lunboImgFileName.length());
				UploadFileUtil.uploadOneFile(lunboFileName, lunboImg, lunboRealpath);
				news.setLunboImg(Constant.PATH_IMG_LUNBO+"/"+lunboFileName);
			}
			news.setAddTime(new Date());
			NewsCategory news_category = newsCategoryDao.findById(news.getCategory().getId());
			news.setCategory(news_category);
			newsDao.saveOrUpdate(news);
			msg.setMsgFlag(true);
			msg.setMsgStr("保存成功！");
		} catch (Exception e) {
			msg.setMsgFlag(false);
			msg.setMsgStr("保存失败：" + e.toString());
			LOG.info(e);
		}
		return msg;
	}

	@Override
	public Message updateNews(News news, File suolveImg, String suolveImgFileName, File lunboImg, String lunboImgFileName) {
		Message msg = new Message();
		try {
			//---------取出未更新前的数据（防止因没有上传图片而覆盖正确的数据）---------------
			News oldNews = newsDao.findById(news.getNewsId());
			//---------缩略图上传（如果没上传则取原数据库内容保存）--------------
			if(suolveImg != null && !"".equals(suolveImg)){
				String suolveRealpath = ServletActionContext.getServletContext().getRealPath(Constant.PATH_IMG_SUOLVE);
				String suolveFileName=null ;
				suolveFileName=UUID.randomUUID().toString()+suolveImgFileName.substring(suolveImgFileName.lastIndexOf('.'), suolveImgFileName.length());
				UploadFileUtil.uploadOneFile(suolveFileName, suolveImg, suolveRealpath);
				news.setImgURL(Constant.PATH_IMG_SUOLVE+"/"+suolveFileName);
			}else{
				news.setImgURL(oldNews.getImgURL());
			}
			//---------轮播图上传（如果没上传则取原数据库内容保存）---------------
			if(lunboImg != null && !"".equals(lunboImg)){
			String lunboRealpath = ServletActionContext.getServletContext().getRealPath(Constant.PATH_IMG_LUNBO);
			String lunboFileName=null ;
			lunboFileName=UUID.randomUUID().toString()+lunboImgFileName.substring(lunboImgFileName.lastIndexOf('.'), lunboImgFileName.length());
			UploadFileUtil.uploadOneFile(lunboFileName, lunboImg, lunboRealpath);
			news.setLunboImg(Constant.PATH_IMG_LUNBO+"/"+lunboFileName);
			}else{
				news.setLunboImg(oldNews.getLunboImg());
			}
			
			news.setAddTime(oldNews.getAddTime());
			NewsCategory news_category = newsCategoryDao.findById(news.getCategory().getId());
			news.setCategory(news_category);
			newsDao.update(news);
			msg.setMsgFlag(true);
			msg.setMsgStr("保存成功！");
		} catch (Exception e) {
			msg.setMsgFlag(false);
			msg.setMsgStr("保存失败：" + e.toString());
			LOG.info(e);
		}
		return msg;
	}
	
	@Override
	public Message removeNews(Integer id) {
		Message msg = new Message();
		//List<NewsCategory> newsCategorys=new ArrayList<NewsCategory>();
		News news =newsDao.findById(id);
			try{
				newsDao.delete(news);
				msg.setMsgFlag(true);
				msg.setMsgStr("删除成功！");
			}catch (Exception e) {
				msg.setMsgFlag(false);
				msg.setMsgStr("删除失败："+e);
			}
		return msg;
	}

	@Override
	public News newsModifyInfo(Integer id) {
		News news=null;
		try{
			news=newsDao.findById(id);
			if(news.getImgURL() != null && !"".equals(news.getImgURL())){
				news.setImgURL(news.getImgURL().indexOf("/")==0 ? news.getImgURL().substring(1) : news.getImgURL());
			}
			if(news.getLunboImg() != null && !"".equals(news.getLunboImg())){
				news.setLunboImg(news.getLunboImg().indexOf("/")==0 ? news.getLunboImg().substring(1) : news.getLunboImg());
			}
//			news.setContent(htmlspecialchars(news.getContent()));
		}catch (Exception e) {
			e.printStackTrace();
		}
		return news;
	}
	
	/**
	 * 	判断是否为图片类型
	 */
	@Override
	public boolean isImage(String imgType) {
		Boolean flag=true;
		if(!ValidatorUtil.isImage(imgType)){
			flag=false;
		}
		return flag;
	}

	
	/**
	 *  判断图片的大小是否超过了预期值
	 */
	@Override
	public boolean isFitSize(File img) {
		boolean flag=true;
		if(img.length()>Constant.SIZE_UPLOAD_IMG){
			flag=false;
		}
		return flag;
	}

	@Override
	public List<NewsVO> getVo(List<News> newsList,String... flag) {
		List<NewsVO> NewsVoList = new ArrayList<NewsVO>();
		NewsVO newsVo = new NewsVO();
		for (News news : newsList) {
			newsVo = new NewsVO();
			newsVo.setAddTime(news.getAddTime());
			if(flag.length > 0 && "needContent".equals(flag[0])){
				newsVo.setContent(news.getContent());
			}
			newsVo.setImgURL(news.getImgURL());
			newsVo.setLunboImg(news.getLunboImg());
			newsVo.setLunboFlag(news.isLunboFlag());
			newsVo.setNewsId(news.getNewsId());
			newsVo.setStatus(news.getStatus());
			newsVo.setSummary(news.getSummary());
			newsVo.setTitle(news.getTitle());
			if(news.getCategory() != null && !"".equals(news.getCategory())){
				newsVo.setCategoryId(news.getCategory().getId().toString());
				newsVo.setCategoryName(news.getCategory().getName());
			}
			NewsVoList.add(newsVo);
		}
		
		return NewsVoList;
	}

	@Override
	public long getCount(Integer category){
		String sql;
		if (category == null || "".equals(category)) {
			sql = "select count(*) from News as news";
		} else {
			sql = "select count(*) from News as news where news.category.id = '"+category+"'";
		}
		return (Long)newsDao.findByHql(sql).get(0);
	}
	
}
